<template>
	<up-popup :show="showPopup" mode="bottom" round="10" @close="closePopup" :safeAreaInsetBottom="true">
		<view class="picker-header">
			<view class="cancel btn" @click="closePopup">取消</view>
			<view class="confirm btn" @click="confirmSelection">确认</view>
		</view>

		<picker-view :value="pickerValue" @change="handlePickerChange" indicator-style="height: 50px;"
			class="picker-view">
			<!-- 年份列 -->
			<picker-view-column>
				<view v-for="(year, index) in years" :key="index" class="picker-item">
					{{ year }}年
				</view>
			</picker-view-column>

			<!-- 月份列 -->
			<picker-view-column v-if="type == 3 || type == 2">
				<view v-for="(month, index) in months" :key="index" class="picker-item">
					{{ month }}月
				</view>
			</picker-view-column>

			<!-- 日期列 -->
			<picker-view-column v-if="type == 3">
				<view v-for="(day, index) in days" :key="index" class="picker-item">
					{{ day }}日
				</view>
			</picker-view-column>
		</picker-view>
	</up-popup>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue'

	const props = defineProps({
		// 控制显示/隐藏
		show: {
			type: Boolean,
			default: false
		},
		// 默认选中的日期（格式：YYYY-MM-DD）
		defaultDate: {
			type: String,
			default: ''
		},
		// 起始年份
		startYear: {
			type: Number,
			default: 1900
		},
		// 结束年份
		endYear: {
			type: Number,
			default: new Date().getFullYear() + 10
		},
		// 1按年 2按月 按日
		type: {
			type: [Number,String],
			default: 3
		},
	})

	const emit = defineEmits(['update:show', 'confirm', 'close'])

	const showPopup = ref(false)
	const pickerValue = ref([0, 0, 0])
	const selectedYear = ref('')
	const selectedMonth = ref('')
	const selectedDay = ref('')

	// 生成年份数组
	const years = computed(() => {
		const arr = []
		for (let year = props.startYear; year <= props.endYear; year++) {
			arr.push(year)
		}
		return arr
	})

	// 生成月份数组（1-12）
	const months = computed(() => {
		return Array.from({
			length: 12
		}, (_, i) => i + 1)
	})

	// 根据选择的年月生成日期数组
	const days = computed(() => {
		if (!selectedYear.value || !selectedMonth.value) return []

		const daysInMonth = new Date(
			selectedYear.value,
			selectedMonth.value,
			0
		).getDate()

		return Array.from({
			length: daysInMonth
		}, (_, i) => i + 1)
	})

	// 初始化选择器
	const initPicker = () => {
		const now = new Date()
		let year = now.getFullYear()
		let month = now.getMonth() + 1
		let day = now.getDate()

		// 如果有默认日期
		if (props.defaultDate) {
			const [y, m, d] = props.defaultDate.split('-')
			year = parseInt(y, 10)
			month = parseInt(m, 10) || 1
			day = parseInt(d, 10) || 1
		}

		// 设置选中值
		selectedYear.value = year
		selectedMonth.value = month
		selectedDay.value = day

		// 计算索引位置
		const yearIndex = years.value.indexOf(year)
		const monthIndex = months.value.indexOf(month)
		const dayIndex = days.value.indexOf(day)

		pickerValue.value = [
			yearIndex > -1 ? yearIndex : 0,
			monthIndex > -1 ? monthIndex : 0,
			dayIndex > -1 ? dayIndex : 0
		]
	}

	// 处理选择器变化
	const handlePickerChange = (e) => {
		const values = e.detail.value
		pickerValue.value = values

		selectedYear.value = years.value[values[0]]
		selectedMonth.value = months.value[values[1]]

		// 确保日期在有效范围内
		const maxDay = days.value.length
		const currentDay = days.value[values[2]] || 1
		selectedDay.value = Math.min(currentDay, maxDay)

		// 更新日期索引
		const dayIndex = Math.min(values[2], maxDay - 1)
		pickerValue.value = [values[0], values[1], dayIndex]
	}

	// 确认选择
	const confirmSelection = () => {
		// const formattedDate =
		// 	`${selectedYear.value}-${selectedMonth.value.toString().padStart(2, '0')}-${selectedDay.value.toString().padStart(2, '0')}`
		let formattedDate = ''
		if (props.type == 1) {
			formattedDate = `${selectedYear.value}`
		} else if (props.type == 2) {
			formattedDate = `${selectedYear.value}-${selectedMonth.value.toString().padStart(2, '0')}`
		} else if (props.type == 3) {
			formattedDate =
				`${selectedYear.value}-${selectedMonth.value.toString().padStart(2, '0')}-${selectedDay.value.toString().padStart(2, '0')}`
		}
		emit('confirm', formattedDate)
		closePopup()
	}

	// 关闭弹窗
	const closePopup = () => {
		showPopup.value = false
		emit('update:show', false)
		emit('close')
	}

	// 监听显示状态变化
	watch(() => props.show, (val) => {
		showPopup.value = val
		if (val) {
			// 延迟初始化确保DOM渲染完成
			setTimeout(initPicker, 50)
		}
	})

	// 监听年月变化（更新日期列）
	watch([selectedYear, selectedMonth], () => {
		// 确保日期不超过当月最大值
		const maxDay = days.value.length
		if (selectedDay.value > maxDay) {
			selectedDay.value = maxDay
		}

		// 更新日期索引
		const dayIndex = Math.min(
			pickerValue.value[2],
			maxDay - 1
		)

		pickerValue.value = [
			pickerValue.value[0],
			pickerValue.value[1],
			dayIndex
		]
	})
</script>

<style scoped lang="scss">
	.picker-header {
		display: flex;
		justify-content: space-between;

		.btn {
			padding: 30rpx;
			font-size: 32rpx;
		}

		.cancel {
			color: #CCCCCC;
		}

		.confirm {
			color: #F5564D;
		}
	}

	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}

	.picker-item {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 50px;
		font-size: 34rpx;
		color: #333;
	}
</style>